import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createHtmlPlugin } from 'vite-plugin-html'
import inject from '@rollup/plugin-inject'
import topLevelAwait from 'vite-plugin-top-level-await'
//这个配置 为了在html中使用 环境变量
const getViteEnv = (mode, target) => {
  return loadEnv(mode, process.cwd())[target]
}
// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  // build: {
  //   chunkSizeWarningLimit: 1500,
  //   rollupOptions: {
  //     output: {
  //       manualChunks(id) {
  //         if (id.includes('node_modules')) {
  //           return id
  //             .toString()
  //             .split('node_modules/.pnpm/')[1]
  //             .split('/')[0]
  //             .toString()
  //         }
  //       },
  //     },
  //   },
  // },
  plugins: [
    vue(),
    topLevelAwait({
      // The export name of top-level await promise for each chunk module
      promiseExportName: '__tla',
      // The function to generate import names of top-level await promise in each chunk module
      promiseImportName: (i) => `__tla_${i}`,
    }),
    inject({
      $: 'jquery', // 这里会自动载入 node_modules 中的 jquery
      jQuery: 'jquery',
      'windows.jQuery': 'jquery',
    }),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    createHtmlPlugin({
      inject: {
        data: {
          //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
          title: getViteEnv(process.env, 'VITE_APP_TITLE'),
        },
      },
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  server: {
    port: 3333,
    proxy: {
      '/api': {
        target: 'http://58.210.32.10:9022/bsApi',
        ws: true,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/mapApi': {
        target:
          'http://58.210.32.10:6080/arcgis/rest/services/KSSW_DATA/ZT_PCGW_YS/MapServer/3/query',
        ws: true,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/mapApi/, ''),
      },
      '/baiduApi': {
        target: 'https://api.map.baidu.com/place/v2',
        ws: true,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/baiduApi/, ''),
      },
    },
  },

  define: {
    'process.env': {},
  },
  // css: {
  //   preprocessorOptions: {
  //     scss: {
  //       additionalData: '@import "./src/assets/style/main.scss";',
  //     },
  //   },
  // },
})
